/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.daikai.tongda.service;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.third.aliyunocr.utils.HttpUtils;
import org.jeecg.modules.third.daikai.tongda.dto.ParamDTO;
import org.jeecg.modules.third.dongjiang.tax.system.utils.HttpUtil;
import org.jeecg.modules.third.daikai.tongda.constant.TongdaConstant;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsPackage: org.jeecg.modules.third.tongda
 * @Author: duanlikao
 * @CreateTime: 2022-08-16 10:14
 * @Description: 通达代开
 * @Version: 1.0
 */
@Service
public class TongdaApiService {

    @Autowired
    private RedisUtil redisUtil;

    private static final Logger LOGGER = LoggerFactory.getLogger(TongdaApiService.class);


    /**
     * 获取系统Token
     * @return
     */
    private String getToken(){
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null || !systemConfig.getTongdaIzUse()){
            throw new JeecgBootException("通达服务暂未开启,请联系管理。");
        }

        Object tokenObject  =
                redisUtil.hasKey(TongdaConstant.TONGDA_API_TOKEN_KEY) ?
                        redisUtil.get(TongdaConstant.TONGDA_API_TOKEN_KEY) : null;
        if(tokenObject != null){
            return tokenObject.toString();
        }
        try {
            String url = systemConfig.getTongdaUrl()+ "/api/merchant/login";
            Map<String, String> map = new HashMap<>();
            map.put("username",systemConfig.getTongdaUsername());
            map.put("password",systemConfig.getTongdaPassword() );

            String jsonString = JSONObject.toJSONString(map);
            String res = HttpUtil.doNewPost(url, jsonString);
            if(StringUtils.isEmpty(res)){
                LOGGER.info("TongdaApiService getToken result | {}" ,res);
                throw new JeecgBootException("TongdaApiService getToken 失败");
            }
            JSONObject result = JSONObject.parseObject(res);
            Integer code = result.getInteger("code") ;
            Object data = result.get("data");
            if( code == 200  && data != null){
                JSONObject resultDataObject = result.getJSONObject("data");
                if(resultDataObject == null){
                    throw new JeecgBootException("获取token失败" );
                }
                String token =  resultDataObject.getString("token");
                if(StringUtils.isEmpty(token)){
                    throw new JeecgBootException("获取token失败" );
                }
                redisUtil.set(TongdaConstant.TONGDA_API_TOKEN_KEY, token, TongdaConstant.TONGDA_API_TOKEN_KEY_EXPIRE);
                return token;
            }else{
                String message = result.getString("message") ;
                throw new JeecgBootException(message);
            }
        } catch (Exception e) {
            LOGGER.info("TongdaApiService getToken Exception | {}" ,e.getMessage());
            throw new JeecgBootException(e.getMessage() );
        }

    }

    //业务接口认证公共头部
    private Map<String, String> getHeaders(String token){
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization",  token);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        headers.put("Accept", "application/json; charset=UTF-8");
        return headers;
    }

    /**
     *
     * @param paramDTO
     * @return
     */
    public String waybillPush(ParamDTO paramDTO){
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null || !systemConfig.getTongdaIzUse()){
            throw new JeecgBootException("通达服务暂未开启,请联系管理。");
        }
        if(paramDTO == null){
            throw new JeecgBootException("提交数据不能为空！");
        }

        String token = getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("通达服务Token为空！");
        }

        Map<String, String> headers = getHeaders(token);
        Map<String, String> querys = new HashMap<>();
        String bodys = JSONObject.toJSONString(paramDTO);
        String path = "/api/merchant/waybill/push";
        LOGGER.info("waybillPush url :{} bodys :{}", systemConfig.getTongdaUrl()+ path , bodys);
        try {
            HttpResponse response = HttpUtils.doPost(systemConfig.getTongdaUrl(),  path, "POST", headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat == 200){
                String res = EntityUtils.toString(response.getEntity(),"UTF-8");
                LOGGER.info("waybillPush res_obj :{} ",res);
                return res;
            }else{
                LOGGER.info("waybillPush Http code: {}  | http header error msg: {} | Http body error msg: {}",
                        stat, response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));
                throw new JeecgBootException("HTTP请求失败！" + stat);
            }
        } catch (Exception e) {
            LOGGER.info("waybillPush Exception :{} ",e.getMessage());
            throw new JeecgBootException("操作失败！" + e.getMessage());
        }

    }
}
